// 学习数据管理工具
const StudyManager = {
  // 记录学习记录
  recordStudy: function(questionId, isCorrect, category, title) {
    const studyHistory = wx.getStorageSync('studyHistory') || [];
    const now = new Date();
    
    // 查找今天是否已有记录
    const today = now.toDateString();
    let todayRecord = studyHistory.find(record => {
      const recordDate = new Date(record.timestamp).toDateString();
      return recordDate === today && record.category === category;
    });
    
    if (todayRecord) {
      // 更新今天的记录
      todayRecord.questionCount += 1;
      if (isCorrect) {
        todayRecord.correctCount += 1;
      }
      todayRecord.rate = Math.round((todayRecord.correctCount / todayRecord.questionCount) * 100) + '%';
    } else {
      // 创建新记录
      todayRecord = {
        id: Date.now(),
        date: this.formatDate(now),
        time: this.formatTime(now),
        timestamp: now.getTime(),
        category: category,
        title: title,
        questionCount: 1,
        correctCount: isCorrect ? 1 : 0,
        rate: isCorrect ? '100%' : '0%',
        duration: '1分钟',
        status: 'completed'
      };
      studyHistory.unshift(todayRecord);
    }
    
    wx.setStorageSync('studyHistory', studyHistory);
    
    // 如果答错了，添加到错题本
    if (!isCorrect) {
      this.addToWrongQuestions(questionId, category, title);
    }
  },

  // 添加到错题本
  addToWrongQuestions: function(questionId, category, title) {
    const wrongQuestions = wx.getStorageSync('wrongQuestions') || [];
    
    // 检查是否已存在
    const existingIndex = wrongQuestions.findIndex(q => q.id === questionId);
    
    if (existingIndex !== -1) {
      // 更新错题记录
      wrongQuestions[existingIndex].wrongCount += 1;
      wrongQuestions[existingIndex].wrongTime = this.formatDate(new Date());
    } else {
      // 添加新错题
      const wrongQuestion = {
        id: questionId,
        category: category,
        title: title,
        wrongCount: 1,
        wrongTime: this.formatDate(new Date()),
        mastered: false,
        reviewed: false
      };
      wrongQuestions.push(wrongQuestion);
    }
    
    wx.setStorageSync('wrongQuestions', wrongQuestions);
  },

  // 添加到收藏
  addToFavorites: function(questionId, category, title, difficulty) {
    const favorites = wx.getStorageSync('favorites') || [];
    
    // 检查是否已收藏
    const existingIndex = favorites.findIndex(f => f.id === questionId);
    
    if (existingIndex === -1) {
      const favorite = {
        id: questionId,
        category: category,
        title: title,
        difficulty: difficulty,
        difficultyText: this.getDifficultyText(difficulty),
        completed: false,
        favoriteTime: this.formatDate(new Date())
      };
      favorites.push(favorite);
      wx.setStorageSync('favorites', favorites);
      return true;
    }
    
    return false;
  },

  // 从收藏中移除
  removeFromFavorites: function(questionId) {
    const favorites = wx.getStorageSync('favorites') || [];
    const newFavorites = favorites.filter(f => f.id !== questionId);
    wx.setStorageSync('favorites', newFavorites);
  },

  // 检查是否已收藏
  isFavorited: function(questionId) {
    const favorites = wx.getStorageSync('favorites') || [];
    return favorites.some(f => f.id === questionId);
  },

  // 格式化日期
  formatDate: function(date) {
    const today = new Date();
    const yesterday = new Date(today.getTime() - 24 * 60 * 60 * 1000);
    
    if (date.toDateString() === today.toDateString()) {
      return '今天';
    } else if (date.toDateString() === yesterday.toDateString()) {
      return '昨天';
    } else {
      return date.toLocaleDateString();
    }
  },

  // 格式化时间
  formatTime: function(date) {
    const hours = date.getHours().toString().padStart(2, '0');
    const minutes = date.getMinutes().toString().padStart(2, '0');
    return `${hours}:${minutes}`;
  },

  // 获取难度文本
  getDifficultyText: function(difficulty) {
    const difficultyMap = {
      'easy': '简单',
      'medium': '中等',
      'hard': '困难'
    };
    return difficultyMap[difficulty] || '未知';
  },

  // 获取学习统计
  getStudyStats: function() {
    const studyHistory = wx.getStorageSync('studyHistory') || [];
    const wrongQuestions = wx.getStorageSync('wrongQuestions') || [];
    const favorites = wx.getStorageSync('favorites') || [];
    
    // 计算学习天数
    const studyDays = new Set(studyHistory.map(record => record.date)).size;
    
    // 计算总题数
    const totalQuestions = studyHistory.length;
    
    // 计算正确率
    let correctCount = 0;
    studyHistory.forEach(record => {
      correctCount += record.correctCount || 0;
    });
    const correctRate = totalQuestions > 0 ? Math.round((correctCount / totalQuestions) * 100) + '%' : '0%';
    
    return {
      studyDays: studyDays,
      totalQuestions: totalQuestions,
      correctRate: correctRate,
      wrongCount: wrongQuestions.length,
      favoriteCount: favorites.length
    };
  }
};

module.exports = StudyManager; 